import { MamisCopilotWidget } from './components/MamisCopilotWidget';
import type { MamisCopilotConfig } from './types/config';
import { defaultConfig } from './types/config';
import { ShadowDOMManager } from './isolation/ShadowDOMManager';

/**
 * 全局MamisCopilot对象
 */
class MamisCopilot {
  private static instance: MamisCopilot | null = null;
  private widget: MamisCopilotWidget | null = null;
  private shadowManager: ShadowDOMManager | null = null;
  private config: MamisCopilotConfig = defaultConfig;

  /**
   * 获取单例实例
   */
  static getInstance(): MamisCopilot {
    if (!MamisCopilot.instance) {
      MamisCopilot.instance = new MamisCopilot();
    }
    return MamisCopilot.instance;
  }

  /**
   * 从后台获取配置
   * @param url 配置接口地址
   * @param apiKey API密钥
   * @returns 配置对象
   */
  async fetchConfig(url: string, apiKey: string): Promise<Partial<MamisCopilotConfig>> {
    try {
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${apiKey}`,
        },
      });

      if (!response.ok) {
        console.error(`HTTP error! status: ${response.status}`);
        return {};
      }

      const result = await response.json();

      // 检查后台返回的标准格式
      if (result.code !== 0) {
        console.error(result.msg || 'Failed to fetch config');
        return {};
      }

      // 返回配置数据
      return result.data || {};
    } catch (error) {
      console.error('Failed to fetch config:', error);
      return {};
    }
  }

  /**
   * 初始化智能助手
   */
  async init(config: Partial<MamisCopilotConfig> = {}) {
    const { configUrl, publicApiKey } = config;

    let copilotConfig: Partial<MamisCopilotConfig> = {};
    if (configUrl && publicApiKey) {
      try {
        copilotConfig = await this.fetchConfig(configUrl, publicApiKey);
      } catch (error) {
        console.error('Failed to fetch config:', error);
      }
    }

    // 深度合并配置
    this.config = {
      ...defaultConfig,
      ...config,
      ...copilotConfig,
      popup: { ...defaultConfig.popup, ...config.popup, ...copilotConfig.popup },
      suggestions: {
        ...defaultConfig.suggestions,
        ...config.suggestions,
        ...copilotConfig.suggestions,
      },
    };

    // 等待DOM加载完成
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => {
        this.createWidget();
      });
    } else {
      this.createWidget();
    }
  }

  /**
   * 创建组件
   */
  private createWidget(): void {
    try {
      // 创建Shadow DOM管理器
      this.shadowManager = new ShadowDOMManager({
        containerId: 'mamis-copilot-root',
        mode: this.config.isolation.shadowDOMMode,
      });

      // 创建组件实例
      this.widget = new MamisCopilotWidget(this.config, this.shadowManager);

      // 渲染组件
      this.widget.render();

      // 触发就绪回调
      if (this.config.onReady) {
        this.config.onReady();
      }

      console.log('麦米思 AI 助手 initialized successfully');
    } catch (error) {
      console.error('Failed to initialize 麦米思 AI 助手:', error);
      if (this.config.onError) {
        this.config.onError(error as Error);
      }
    }
  }

  /**
   * 销毁组件
   */
  destroy(): void {
    if (this.widget) {
      this.widget.destroy();
      this.widget = null;
    }
    if (this.shadowManager) {
      this.shadowManager.destroy();
      this.shadowManager = null;
    }
  }

  /**
   * 获取当前配置
   */
  getConfig(): MamisCopilotConfig {
    return this.config;
  }

  /**
   * 更新配置
   */
  updateConfig(newConfig: Partial<MamisCopilotConfig>): void {
    this.config = { ...this.config, ...newConfig };
    if (this.widget) {
      this.widget.updateConfig(this.config);
    }
  }
}

// 将MamisCopilot暴露到全局
declare global {
  interface Window {
    MamisCopilot: typeof MamisCopilot;
  }
}

window.MamisCopilot = MamisCopilot;

// 自动初始化逻辑（用于script标签集成）
if (typeof document !== 'undefined' && document.currentScript) {
  const script = document.currentScript as HTMLScriptElement;
  const runtimeUrl = script.getAttribute('data-runtime-url') || defaultConfig.runtimeUrl;
  const configUrl = script.getAttribute('data-config-url') || defaultConfig.configUrl;
  const publicApiKey = script.getAttribute('data-api-key');
  const autoInit = script.getAttribute('data-auto-init');

  if (autoInit !== 'false' && publicApiKey) {
    const instance = MamisCopilot.getInstance();
    instance.init({ publicApiKey, runtimeUrl, configUrl });
  }
}

// 导出类型和实例
export { MamisCopilot, MamisCopilotConfig };
export default MamisCopilot.getInstance();
